package com.ruiyou.ub;

import android.content.Intent;
import android.graphics.Bitmap;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.util.Arrays;
import java.util.List;

/**
 * 辅助WebView处理各种通知与请求事件
 **/
public class UWebViewClient extends WebViewClient {

    private final UWebView uwv;
    private UWebView.StateListener mListener;

    public UWebViewClient(UWebView uwv) {
        this.uwv = uwv;
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        if ((mListener = uwv.getStateListener()) != null) {
            mListener.onStateChanged(uwv,
                    mListener.STATE_STARTED, url, favicon);
        }

    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        if ((mListener = uwv.getStateListener()) != null) {
            mListener.onStateChanged(uwv, mListener.STATE_FINISHED, url);
        }
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        List<String> schemes = Arrays.asList("http", "https", "file", "content");
        String scheme = request.getUrl().getScheme();
        if (scheme != null && schemes.contains(scheme.toLowerCase())) {
            if (scheme.equalsIgnoreCase("http")) {
                uwv.loadUrl(request.getUrl().toString().replaceFirst("\\w{4}", "https"));
                return true;
            }
            return false;
        } // 处理自定义协议
        if (uwv.getAllowCallOtherApp()) {
            try {
                Intent it = new Intent();
                it.setAction(Intent.ACTION_VIEW);
                it.setData(request.getUrl());
                uwv.getContext().startActivity(it);
            } catch (Exception ignore) {
            }
        }
        return true;
    }
}
